package com.oglvip.business.web.controller;

import com.github.bingoohuang.patchca.service.Captcha;
import com.github.bingoohuang.patchca.service.CaptchaService;
import com.oglvip.business.consts.common.Consts;
import com.oglvip.business.dto.ResponseData;
import com.oglvip.business.extend.exception.ArgsValidException;
import com.oglvip.business.remote.service.api.StoreAccountService;
import com.oglvip.business.util.MatchUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @auther hanchao
 * @date 2016/12/6 12:53
 */
@Controller
@RequestMapping("/validcode")
public class ValidCodeController {
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private StoreAccountService storeAccountService;

    @RequestMapping(value="/img",method = RequestMethod.GET)
    public ResponseEntity<byte[]> getImgCode(HttpSession session) throws IOException {
        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.PRAGMA,"No-cache");
        header.add(HttpHeaders.CACHE_CONTROL,"no-cache");
        header.add(HttpHeaders.EXPIRES,"0");
        header.add(HttpHeaders.CONTENT_TYPE,"image/jpeg");

        Captcha captcha = captchaService.getCaptcha();
        session.setAttribute(Consts.CAPTCHA,captcha.getWord());

        BufferedImage img = captcha.getImage();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(img,"jpeg",bos);
        return new ResponseEntity<byte[]>(bos.toByteArray(),header, HttpStatus.OK);
    }

    @RequestMapping("/phone")
    @ResponseBody
    public ResponseData getPhoneCode(@Pattern(regexp = "^[1][34578][0-9]{9}$") @Validated String phone, Integer type){
        if (! MatchUtil.isPhoneNo(phone) || type == null) {
            throw new ArgsValidException("wrong args");
        }
        return storeAccountService.createCaptcha(phone,type);
//        ResponseData data = new ResponseData();
//        //data.setResponseCode(ResponseCode.SUCCESS);
//        data.setCode(1);
//        data.setMessage("asasd"+System.currentTimeMillis());
//        return data;
    }

}
